//
//  QTBClientCallCore.m
//  QTBClientDemo
//
//  Created by fan on 2021/10/20.
//

#import "QTBClientCallCore.h"
#import <CloudCallBaseFrame/CommonFrame.h>
#import <objc/runtime.h>
#import "LCPatientModel.h"


NSNotificationName const CallingDidConnectNotification = @"CallingDidConnectNotification";
NSNotificationName const CallingDidErrorNotification = @"CallingDidErrorNotification";
NSNotificationName const CallingDidEndNotification = @"CallingDidEndNotification";
NSNotificationName const CallingTimeChangedNotification = @"CallingTimeChangedNotification";
NSNotificationName const NativeClickActionNotification = @"NativeClickActionNotification";
NSNotificationName const GetPatientsInfoNotification = @"GetPatientsInfoNotification";
NSNotificationName const SetCurrentPatientNotification = @"SetCurrentPatientNotification";



static QTBClientCallCore *shareCallCore = nil;

@interface QTBClientCallCore()<QtbClientListenerDelegate>

@property (nonatomic, copy) QTBClientCallCoreCompletion loginCompletion;

@property (nonatomic, copy) QTBClientStartCallCallBack startCallCallBack;

@property (nonatomic, weak)   id <QTBClientCallSessionInDelegate> receiveCallDelegate;

@property (nonatomic, strong) QtbClient *qtbClient;

@property (nonatomic, strong) NSString *agentName;
@property (nonatomic, strong) NSString *pwd;
/**  打破timer强引用target  */
@property (nonatomic, strong) LocateTempTarget *target;
@property (nonatomic, strong)NSTimer *timer;
@property (nonatomic, strong)LCPatientModel *currentPatient;

@end

@implementation QTBClientCallCore

+(instancetype)shareCallCore {
    if (!shareCallCore) {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            shareCallCore = [[QTBClientCallCore alloc] init];
            shareCallCore.qtbClient = [QtbClient shareClient];
            shareCallCore.currentCall = [[QTBClientCallSession alloc] init];
        });
    }
    return shareCallCore;
}


- (instancetype)init {
    if (self = [super init]) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setCurrentPatientAction:) name:SetCurrentPatientNotification object:nil];
    }
    return self;
}


-(void)setCurrentPatientAction:(NSNotification*)sender{
    LCPatientModel *patient = sender.object;
    if ([patient isKindOfClass:[LCPatientModel class]]) {
        self.currentPatient = patient;
    }
}

-(void)setCallSessionInDelegate:(id <QTBClientCallSessionInDelegate>)delegate {
    self.receiveCallDelegate = delegate;
}

//登录
-(void)login:(NSString *)agent
    password:(NSString *)password
        type:(int)type
        host:(NSString *)host
  completion:(QTBClientCallCoreCompletion)completion {
    self.loginCompletion = completion;
    //先连接websocket 保存账号密码，连接成功再执行登录。
    if ([self.qtbClient connect:host]) {
        [self.qtbClient setClientListener:self];
        self.agentName = agent;
        self.pwd = password;
    }else {
        self.loginCompletion(1, @"连接失败");
    }
}


//登出
-(void)logout:(QTBClientCallCoreCompletion)completion {
    
}


//呼叫坐席
-(void)startCallAgent:(NSString *)agent
           completion:(QTBClientStartCallCallBack)completion {
    self.startCallCallBack = completion;
    _currentCall.status = QTBCallSessionStatusStartCall;
    [self.qtbClient sendCallOtherWithAgent:agent IsVideo:NO];
}

//呼叫外线
-(void)startCallPhone:(NSString *)phone completion:(QTBClientStartCallCallBack)completion {
    self.startCallCallBack = completion;
    [self.qtbClient sendCallWithPhoneNum:phone CallerNum:@""];
    self.currentCall.outbound = YES;
}

//挂断
- (void)sendOnHook {
    self.currentCall.makeHangup = YES;
    [self.qtbClient sendDropCall:self.currentCall.invokeID];
}

//接听
- (void)answerCall {
    [self.qtbClient sendAnswerCall:self.currentCall.invokeID];
}

#pragma QtbClientListenerDelegate

- (void)onConnect {
    [self.qtbClient sendLoginInWithAccount:self.agentName password:self.pwd loginType:AgentANormal Domain:@"36.134.4.156"];
    //    NSLog(@"------------------连接成功");
}

/// 断开连接
- (void)onDisconnect:(int)code{}

/// 登录成功
- (void)onLoginSuccess{
    dispatch_async(dispatch_get_main_queue(), ^{
        if (self.loginCompletion) {
            self.loginCompletion(0, @"登录成功");
        }
    });
}
/// 登录失败
- (void)onLoginError:(int)code desc:(NSString *)desc{
    if (self.loginCompletion) {
        self.loginCompletion(code, desc);
    }
    NSLog(@"登录失败:%d---%@",code,desc);
}

- (void)onLogoutSucces{}
- (void)onLogoutError:(int)code desc:(NSString *)desc{}

/// 被踢下线
- (void)onForceLogout:(int)code desc:(NSString *)desc{
    [MBProgressHUD showMessage:@"坐席被踢下线"];
    [self.qtbClient disConnect];
}

/// 收到呼叫
- (void)onCallIn:(NSString *)from callId:(NSString *)callId callType:(CallType)callType{
    self.currentCall.identifier = from;
    self.currentCall.outbound = NO;
    self.currentCall.status = QTBCallSessionStatusReceiveCall;
    self.currentCall.createTime = [NSDate date];
    self.currentCall.invokeID = callId;
    if ([self.receiveCallDelegate respondsToSelector:@selector(onCallIn:)]) {
        [self.receiveCallDelegate onCallIn:self.currentCall];
    }
}

///转移到我
- (void)onTransferToMe:(NSString *)from callId:(NSString *)callId{
    self.currentCall.identifier = from;
    self.currentCall.outbound = NO;
    self.currentCall.createTime = [NSDate date];
    self.currentCall.invokeID = callId;
    if ([self.receiveCallDelegate respondsToSelector:@selector(onCallIn:)]) {
        [self.receiveCallDelegate onCallIn:self.currentCall];
    }
}

/// 正在外呼
- (void)onCalling:(NSString *)callId{
    self.currentCall.invokeID = callId;
    self.currentCall.outbound = YES;
    self.currentCall.status = QTBCallSessionStatusCalling;
    if (self.startCallCallBack) {
        self.startCallCallBack(0, @"发起呼叫成功，等待对方接听中。。。", self.currentCall);
    }
}
/// 电话建立失败
- (void)onCallError:(int)errorCode desc:(NSString *)desc{
    self.currentCall.status = QTBCallSessionStatusCallError;
    [[NSNotificationCenter defaultCenter] postNotificationName:CallingDidErrorNotification object:nil];
    [self closeTimer];
    [MBProgressHUD showMessage:desc];
    NSLog(@"error: 2222");
}

/// 到达对方,等待对方接听
- (void)onCallEstablished:(NSString *)other callID:(NSString *)callId{
    NSLog(@"waiting: 11111");
}
/// 电话建立成功
- (void)onCallEstablishedReal:(NSString *)callId{
    //    NSLog(@"电话接通！onCallEstablishedReal");
    self.currentCall.status = QTBCallSessionStatusConnect;
    self.currentCall.mediaCreateTime = [NSDate date];
    self.currentCall.invokeID = callId;
    NSLog(@"Connect: 1111");
    [[NSNotificationCenter defaultCenter] postNotificationName:CallingDidConnectNotification object:callId];
    [self openTimer];
}
/// 电话断开成功
- (void)onCallReleased:(NSString *)callID desc:(NSString *)desc{
    if (![callID isEqualToString:self.currentCall.invokeID]) {
        return;
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        self.currentCall.endedDesc = desc;
        if (self.currentCall.status == QTBCallSessionStatusCalling) {
            //主叫
            self.currentCall.status = QTBCallSessionStatusEnding;
        }else if (self.currentCall.status == QTBCallSessionStatusReceiveCall) {
            //被叫
            self.currentCall.status = QTBCallSessionStatusEnding;
        }
        NSLog(@"error: 1111%@", desc);
        /// 挂断绑定通话与患者
        if (self.currentPatient) {
            [self bindCallRequest];
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:CallingDidEndNotification object:callID];
        [WWPortManagerTool defaultTool].patientsArray = nil;
        self.currentPatient = nil;
        [self closeTimer];
        //        if (![desc isEqualToString:@"通话结束"]) {
        //            [MBProgressHUD showMessage:desc];
        //        }
    });
}

-(void)bindCallRequest{
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    dict[@"callId"] = self.currentCall.invokeID;
    dict[@"customerId"] = self.currentPatient.id;
    dict[@"customerMobile"] = self.currentPatient.phone;
    dict[@"customerName"] = self.currentPatient.name;
    dict[@"supplier"] = @"infobird";
    NSString *baseUrl = [LCRequester sharedForApp].afManager.baseURL.absoluteString;
    NSString *url = [NSString stringWithFormat:@"%@/ccc/api/v1/customer/app/add-call-temp-record",baseUrl];
    [[LCRequester sharedForApp] requestWithMethod:HTTP_POST urlString:url parameters:dict finish:^(NSURLSessionDataTask *operation, id responseObject, NSError *error) {
        if (responseObject && [responseObject isKindOfClass:[NSDictionary class]] && responseObject[@"body"]) {
            NSLog(@"上传结果：%@ parameters：%@",responseObject, dict);
        }
    }];
}

- (NSString *)stringValueWithDate:(NSDate *)date {
    NSDateFormatter *dateFormatter = [NSDateFormatter new];
    dateFormatter.timeZone = [NSTimeZone timeZoneWithName:@"GMT"];
    dateFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US"];
    dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:SS";
    return [dateFormatter stringFromDate:date];
}

///
- (void)onQuestionBuild:(NSString *)other TargetType:(TargetType)targetType questionId:(NSString *)questionId{}
///
- (void)onQuestionCancel:(NSString *)questionId{}

//仅发起方
- (void)onQuestionCalling:(NSString *)questionId CallTo:(NSString *)callTo{}
- (void)onQuestionError:(NSString *)questionId CallTo:(NSString *)callTo{}
/// 坐席状态变化
- (void)onStateChanged:(QtbStateType)state{
    self.stateType = state;
}

//发起三方通话结果
- (void)onStartConferenceSuccess{}
- (void)onStartConferenceError:(int)code desc:(NSString *)desc{}
/// 有人离开了三方会议
- (void)onOtherLeaveConference:(NSString *)otherSide{}

- (void)onTimeOut:(NSString *)msg{
    NSLog(@"error: 33333%@", msg);
}
/// 返回媒体建立的类型
- (void)onMediaBuild:(NSString *)type desc:(NSString *)desc{
    NSLog(@"Connect: 22222%@", desc);
    //    [self.currentCall.delegate onMediaBuild:type desc:desc];
}


-(void)openTimer{
    if (self.timer && self.timer.isValid) {
        return;
    }
    self.target = [[LocateTempTarget alloc] init];
    _target.target = self;
    class_addMethod([_target class], @selector(_countDown), class_getMethodImplementation([self class], @selector(refreshTime)),  "v@:");
    self.timer = [NSTimer timerWithTimeInterval:1 target:self.target selector:@selector(_countDown) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    [self.timer setFireDate:[NSDate distantPast]];
}

-(void)closeTimer{
    [self.timer setFireDate:[NSDate distantFuture]];
    self.timer = nil;
}

- (void)refreshTime{
    //    NSLog(@"111111111111111111111");
    NSDate *connectDate = [QTBClientCallCore shareCallCore].currentCall.mediaCreateTime;
    if (connectDate) {
        NSTimeInterval timeout = [[NSDate date] timeIntervalSinceDate:connectDate];
        int hours = (int)(timeout/3600);
        int minute = (int)(timeout-hours*3600)/60;
        int second = timeout-hours*3600-minute*60;
        NSString *time = [NSString stringWithFormat:@"%.2d:%.2d",minute,second];
        if (hours > 0) {
            time = [NSString stringWithFormat:@"%.2d:%@",hours,time];
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:CallingTimeChangedNotification object:time];
    }
}


- (void)_countDown{
    
}


@end
